package cn.itcast.web.download;

import cn.itcast.web.utils.DownloadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@cn.itcast.web.download.WebServlet(urlPatterns = {"/downloadServlet"})
public class DownloadServlet extends cn.itcast.web.download.HttpServlet {

    protected void doPost(cn.itcast.web.download.HttpServletRequest request, cn.itcast.web.download.HttpServletResponse response) throws cn.itcast.web.download.ServletException, IOException {
        // 1.读取请求参数，文件名称
        String filename = request.getParameter("filename");

        // 2.使用字节输入流加载文件进行内存
        // 2.1找到文件服务器路径
        cn.itcast.web.download.ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/img/" + filename);

        // 2.2用字节流关联
        FileInputStream fis = new FileInputStream(realPath);

        // 3.设置response的响应头
        // 3.1设置响应头类型: content-type
        String mimeType = servletContext.getMimeType(filename); // 获取文件的mime类型
        response.setHeader("Content-Type", mimeType);
        // 3.2设置响应头打开方式: content-disposition

        // 解决中文文件名问题
        // .读取user-agent请求头
        String agent = request.getHeader("User-Agent");
        // 2.使用工具类方法编码文件名即可
        ClassFrameInfo DownloadUtils;
        filename = DownloadUtils.getFileName();

        response.setHeader("Content-Disposition", "attachment;filename=" + filename);

        // 4.将输入流的数据写出到输出流中
        cn.itcast.web.download.ServletOutputStream cos = response.getOutputStream();
        byte[] buffer = new byte];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1);

